<template>
  <div>
    <el-upload
      drag
      :action="this.baseApi + '/img/upload'"
      :file-list="fileList"
      :headers="headers"
      :data="{ type: 1 }"
      :multiple="false"
      :limit="1"
      name="files"
      list-type="picture-card"
      :on-success="uploadSuccess"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或
        <em>点击上传</em>
      </div>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script>
import { baseApi, baseImg } from '@/utils'
import { deleteImg } from '@/api/product'
export default {
  props: {
    list: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      headers: {
        Authorization: `Bearer ${this.$store.getters.token}`,
      },
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      baseApi: baseApi,
      baseImgUrl: baseImg,
    }
  },
  watch: {
    list: {
      handler(newVal) {
        this.fileList = newVal
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 上传成功
    uploadSuccess(response) {
      // 回传上传成功数据
      this.$emit('callBack', response.data)
      this.$emit('update:url', response.data[0].url)
      this.$emit('update:thumbnail', response.data[0].thumbnail)
    },

    // 预览
    handlePictureCardPreview(uploadFile) {
      this.dialogImageUrl = uploadFile.url
      this.dialogVisible = true
    },

    // 删除
    handleRemove(uploadFile) {
      let id = uploadFile.response?.data[0]?.id
      if (id) {
        deleteImg(id)
      }
    },
  },
}
</script>
